package com.aishua.aishuawallet.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.aishua.aishuawallet.Constant;
import com.aishua.aishuawallet.R;
import com.aishua.aishuawallet.bean.ReqAuthBean;
import com.aishua.aishuawallet.bean.ResAuthBean;
import com.aishua.aishuawallet.bean.TokenInfo;
import com.aishua.aishuawallet.business.TaskBusiness;
import com.aishua.aishuawallet.engin.IResponseListener;
import com.aishua.aishuawallet.longconnection.ClientSocket;
import com.aishua.aishuawallet.longconnection.SocketFactory;
import com.aishua.aishuawallet.mina.MianManager;
import com.aishua.aishuawallet.mina.MinaResultLIstener;
import com.aishua.aishuawallet.utils.AndroidUtils;
import com.aishua.aishuawallet.utils.CacheUtils;
import com.aishua.aishuawallet.utils.LogUtils;


import org.apache.mina.core.session.IoSession;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by aishua on 2018/8/6.
 */

public class LoginActivity extends BaseActivity {
    private static final String TAG = "LoginActivity-";
    private Context mContext;
    private Toolbar tl_login;
    private TextView toolbar_title;
    private Button btn_login;
    private Button btn_lookfirst;
    private EditText et_phone;
    private EditText et_pw;
    private String phone = null;
    private String pw = null;
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {

                case 3:

                    Bundle bundle = msg.getData();
                    String authtype = (String) bundle.get(Constant.AUTH_TYPE);
                    ResAuthBean resAuthBean = (ResAuthBean) bundle.getSerializable("resAuthBean");
                    successLogin(authtype, resAuthBean);

                    break;
                case 4:

                    Toast.makeText(mContext, "登录失败", Toast.LENGTH_SHORT).show();

                    break;
                case 5:

                    creatWallet();
                    break;
            }

        }
    };


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        mContext = this;
        initToolbar();
        initView();
        initData();

    }

    private void initData() {

        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                phone = et_phone.getText().toString().trim();
                pw = et_pw.getText().toString().trim();
                LogUtils.v(TAG + "phone:" + phone + ",pw:" + pw);
                if (phone.equals("") || pw.equals("") || null == phone || null == pw) {

                    Toast.makeText(mContext, "手机号或者密码为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                TaskBusiness.getInstance().doAuth(LoginActivity.this, "02", "2020", phone, pw, new MinaResultLIstener() {
                    @Override
                    public void messageReceived(IoSession session, Object msg) {

                        MianManager.getManager().shutDown();
                        LogUtils.v(TAG + "resultContent:" + msg.toString());
                        Message message = Message.obtain();
                        Bundle bundle = new Bundle();
                        bundle.putString(Constant.AUTH_TYPE, "02");
                        String msg1 = msg.toString();
                        String result = msg1.substring(74, 76);
                        LogUtils.v(TAG + "result：" + result);
                        if (result.equals("00")) {
                            CacheUtils.putLoginpw(mContext, Constant.PW, pw);
                            CacheUtils.putLoginname(mContext, Constant.PHONE, phone);
                            LogUtils.v(TAG + "result:" + result);
                            String iccid = msg1.substring(76, 96);
                            String cardkey = msg1.substring(96, 352);
                            String tokennum = msg1.substring(352, 354);
                            LogUtils.v(TAG + "tokenum:" + tokennum);
                            int tokenlen = 0;

                            if (Integer.valueOf(tokennum) > 0) {

                                ResAuthBean resAuthBean = new ResAuthBean();
                                List<TokenInfo> tokenInfos = new ArrayList<>();
                                for (int i = 0; i < Integer.valueOf(tokennum); i++) {

                                    int tokenlenindex = Integer.parseInt(msg1.substring(354, 358), 16);
                                    LogUtils.v(TAG + "tokenlenindex:" + tokenlenindex);
                                    String tokenid = msg1.substring(358 + tokenlen, 374 + tokenlen);
                                    LogUtils.v(TAG + "tokenid:" + tokenid);
                                    String tokennamelen = msg1.substring(374 + tokenlen, 376 + tokenlen);
                                    LogUtils.v(TAG + "tokennamelen:" + tokennamelen);
                                    int tokennamelenint = Integer.parseInt(tokennamelen, 16);
                                    LogUtils.v(TAG + "tokennamelenint:" + tokennamelenint);
                                    String tokename = msg1.substring(376 + tokenlen, 376 + tokenlen + tokennamelenint);
                                    LogUtils.v(TAG + "tokename:" + AndroidUtils.unicode2String(tokename));
                                    String tokenaddr = msg1.substring(376 + tokenlen + tokennamelenint, 416 + tokenlen + tokennamelenint);
                                    LogUtils.v(TAG + "tokenaddr:" + tokenaddr);
                                    String cointype = msg1.substring(416 + tokenlen + tokennamelenint, 424 + tokenlen + tokennamelenint);
                                    LogUtils.v(TAG + "cointype:" + cointype);
                                    LogUtils.v(TAG + "tokenlenindex：" + tokenlenindex + "tokenid:" + tokenid + "tokename:" + tokename + "tokenaddr:" + tokenaddr + "cointype:" + cointype);

                                    TokenInfo tokenInfo = new TokenInfo();
                                    tokenInfo.setTokenID(tokenid);
                                    tokenInfo.setTokenName(AndroidUtils.unicode2String(tokename));
                                    tokenInfo.setTokenAddr(tokenaddr);
                                    tokenInfo.setCoinType(cointype);

                                    tokenlen = tokenlenindex;

                                    tokenInfos.add(tokenInfo);
                                    resAuthBean.setTokenNum(tokennum);

                                    resAuthBean.setTokenInfo(tokenInfos);
                                }
                                bundle.putSerializable("resAuthBean", resAuthBean);
                                message.what = Constant.SUCCESS_LOGIN;

                            } else {

                                message.what = Constant.CREAT_WALLET;

                            }

                            bundle.putString("result", result);


                        } else {
//                            message.what = Constant.SUCCESS_LOGIN;

                            message.what = Constant.FAIL_LOGIN;
                        }
                        message.setData(bundle);
                        mHandler.sendMessage(message);

                    }

                    @Override
                    public void exceptionCaught(IoSession session, Throwable cause) {

                        LogUtils.v(TAG + "failmsg:" + cause.getMessage());
                        MianManager.getManager().shutDown();

                    }

                });
            }
        });

        btn_lookfirst.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                TaskBusiness.getInstance().doAuth(LoginActivity.this, "03", "2030", null, null, new MinaResultLIstener() {
                    @Override
                    public void messageReceived(IoSession session, Object msg) {

                        Constant.ISTOURIST = true;
                        LogUtils.v(TAG + "resultContent:" + msg.toString());
                        Message message = Message.obtain();
                        Bundle bundle = new Bundle();
                        bundle.putString(Constant.AUTH_TYPE, "03");
                        String msg1 = msg.toString();
                        String result = msg1.substring(74, 76);


                        LogUtils.v(TAG + "result:" + result);

                        ResAuthBean resAuthBean = new ResAuthBean();
                        List<TokenInfo> tokenInfos = new ArrayList<>();


                        TokenInfo tokenInfo = new TokenInfo();
                        tokenInfo.setTokenID("0000000000000000");
                        tokenInfo.setTokenName(getResources().getString(R.string.tourist));
                        tokenInfo.setTokenAddr("0x0000000000000000000000000000000000000000");
                        tokenInfo.setCoinType("00000000");


                        tokenInfos.add(tokenInfo);
                        resAuthBean.setTokenNum("1");

                        resAuthBean.setTokenInfo(tokenInfos);

                        bundle.putSerializable("resAuthBean", resAuthBean);
                        message.what = Constant.SUCCESS_LOGIN;
                        message.setData(bundle);
                        mHandler.sendMessage(message);
                        MianManager.getManager().shutDown();
                    }

                    @Override
                    public void exceptionCaught(IoSession session, Throwable cause) {

                        LogUtils.v(TAG + "failmsg:" + cause.getMessage());

                    }

                });
            }

        });

    }

    private void successLogin(String authtype, ResAuthBean resAuthBean) {


        Toast.makeText(mContext, "登录成功", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        intent.putExtra("resAuthBean", resAuthBean);

        startActivity(intent);
        finish();

    }


    private void initToolbar() {

        tl_login = findViewById(R.id.tl_login);
        tl_login.setTitle(getResources().getString(R.string.login));

        toolbar_title = findViewById(R.id.toolbar_title);
        toolbar_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(LoginActivity.this, RegistOneActivity.class);
                startActivity(intent);
            }
        });
    }

    private void initView() {


        btn_login = findViewById(R.id.btn_login);
        btn_lookfirst = findViewById(R.id.btn_lookfirst);
        et_phone = findViewById(R.id.et_phone);
        et_pw = findViewById(R.id.et_pw);
        MyTextWatcher1 myTextWatcher1 = new MyTextWatcher1();
        MyTextWatcher2 myTextWatcher2 = new MyTextWatcher2();
        et_phone.addTextChangedListener(myTextWatcher1);
        et_pw.addTextChangedListener(myTextWatcher2);
    }

    private void creatWallet() {

        Toast.makeText(mContext, "创建钱包", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(this, CreatWalletActivity.class);
        startActivity(intent);

    }


    public class MyTextWatcher1 implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            LogUtils.v(TAG + "s:" + s);
            phone = s.toString().trim();
            pw = et_pw.getText().toString().trim();
            canClick(phone, pw);
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    }


    public class MyTextWatcher2 implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            LogUtils.v(TAG + "s:" + s);
            phone = et_phone.getText().toString().trim();
            pw = s.toString().trim();
            canClick(phone, pw);

        }

        @Override
        public void afterTextChanged(Editable s) {


        }
    }

    private void canClick(String phone, String pw) {


        if (null == phone || "".equals(phone) || null == pw || "".equals(pw)) {

            btn_login.setBackground(getDrawable(R.drawable.btn_no_click_auth));
            btn_login.setEnabled(false);

        } else {

            btn_login.setBackground(getDrawable(R.drawable.btn_click_auth));
            btn_login.setEnabled(true);
        }


    }

}
